<template>
    <div>
        <!--批量上传 -->
        <el-dialog v-model="state.uploadDialogVisible" width="80%" @close="state.uploadStutas = false">
            <div v-if="!state.uploadStutas">
                <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="state.headers" action="#"
                    :disabled="state.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                    :auto-upload="false" :before-upload="beforeUpload" drag>
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip text-center" slot="tip">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                    </div>
                </el-upload>
            </div>
            <div v-if="state.uploadStutas">
                <el-table ref="multipleTableRef" :data="paginatedData" style="width: 100%">
                    <el-table-column prop="id" label="ID" width="80" />
                    <el-table-column prop="departmentName" label="部门名称" width="120" align="center" />
                    <el-table-column prop="manage" label="负责人" width="150" align="center" />
                    <el-table-column prop="contact" label="联系电话" width="250" align="center" />
                    <el-table-column prop="departmentDescription" label="简介" align="center" />
                </el-table>

                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="state.parsePage.pageNum" :page-sizes="[5, 10]" :page-size="state.parsePage.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="state.parsePage.total" class="mt-6">
                </el-pagination>
            </div>
            <div slot="footer" class="mt-2 flex flex-row-reverse">
                <el-button @click="state.uploadDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitFileForm" class="me-2">
                    {{ state.uploadStutas ? '导 入' : '确 定' }}
                </el-button>
            </div>
        </el-dialog>
        <!-- 添加新增窗口 -->
        <el-dialog title="新增部门" v-model="state.addDialogVisible" width="50%" @close="state.editForm = {}">
            <el-form ref="addForm" :model="state.editForm" :rules="state.rules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="部门名称" prop="departmentName">
                            <el-input v-model="state.editForm.departmentName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="负责人" prop="manage">
                            <el-input v-model="state.editForm.manage"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="contact">
                            <el-input v-model="state.editForm.contact"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="简介" prop="departmentDescription">
                    <el-input type="textarea" v-model="state.editForm.departmentDescription" :rows="5"
                        :cols="30"></el-input>
                </el-form-item>
                <el-form-item>
                    <div class="flex justify-between">
                        <el-button type="primary" @click="updateRow">提交</el-button>
                        <el-button type="plain" @click="state.addDialogVisible = false">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 编辑用户弹出框 -->
        <el-dialog title="编辑部门" v-model="state.editDialogVisible" width="50%" @close="state.editForm = {}">
            <el-form ref="editForm" :model="state.editForm" :rules="state.rules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="部门名称" prop="departmentName">
                            <el-input v-model="state.editForm.departmentName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="负责人" prop="manage">
                            <el-input v-model="state.editForm.manage"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="contact">
                            <el-input v-model="state.editForm.contact"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="简介" prop="departmentDescription">
                    <el-input type="textarea" v-model="state.editForm.departmentDescription" :rows="5"
                        :cols="30"></el-input>
                </el-form-item>
                <el-form-item>
                    <div class="flex justify-between">
                        <el-button type="primary" @click="updateRow">提交</el-button>
                        <el-button type="plain" @click="state.editDialogVisible = false, state.editForm = {}">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-row class="mb-1">
            <div class="w-full flex justify-end">
                <el-autocomplete v-model="state.stateData" @change="inputSearch" :fetch-suggestions="querySearchAsync"
                    placeholder="请输入关键字" @select="handleSelect" class="mr-2">
                    <template #suffix>
                        <el-icon color="#000">
                            <Search />
                        </el-icon>
                    </template>
                </el-autocomplete>
                <el-button type="info" :icon="Avatar" @click="state.uploadDialogVisible = true">导入部门数据</el-button>
                <el-button type="warning" :icon="Download" @click="downloadUser('downLoad')">下载模板</el-button>
                <el-button type="success" :icon="Upload" @click="downloadUser()">导出excel表格</el-button>
                <el-button type="danger" :icon="Delete" @click="deleteAll">批量删除</el-button>
                <el-button type="primary" :icon="Plus" @click="state.addDialogVisible = true">新增</el-button>
            </div>
        </el-row>
        <el-table :data="state.departmentList" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" fixed="left" width="50" align="center" />
            <el-table-column prop="DepartmentName" label="部门名称" width="120" align="center" />
            <el-table-column prop="Manage" label="负责人" width="150" align="center" />
            <el-table-column prop="Contact" label="联系电话" width="180" align="center" />
            <el-table-column prop="DepartmentDescription" label="简介" width="250" align="center" />
            <el-table-column fixed="right" label="操作" align="center">
                <template #default="scope">
                    <el-button link type="warning" size="small" @click.prevent="openUpdata(scope.row)">
                        <el-icon>
                            <EditPen />
                        </el-icon>
                        编辑
                    </el-button>
                    <el-button link type="danger" size="small" @click.prevent="deleteRow(scope.row)">
                        <el-icon>
                            <DeleteFilled />
                        </el-icon>
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handlehSizeChange" @current-change="handlehCurrentChange" :page-sizes="[5, 8, 10]"
            :page-size="state.pageSize" layout="total, jumper, prev, pager, next, sizes" :total="state.total" class="mt-2">
        </el-pagination>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref, computed } from 'vue'
import { downloadTemplateUser, downloadUserData, analysisExcel } from '../utils/tableMethod.js'
import { departmentRead, findAllDepartmentList, departmentUpdate, departmentDelete, departmentCreate, departmentReadAll } from '../api/department/department.js'
import { DeleteFilled, EditPen, Hide, ZoomIn, Avatar, UploadFilled, Upload, Download, Delete, Plus, Search, Lock } from '@element-plus/icons-vue'
const state = reactive({
    departmentList: [],
    departmentNames: [],
    editForm: {
        departmentID: '',
        departmentName: '',
        departmentDescription: '',
        manage: '',
        contact: '',
    },
    editDialogVisible: false,
    addDialogVisible: false,
    selectedIds: [],//选中的id
    // 分页
    total: "",
    pageNum: 1,
    pageSize: 5,
    stateData: '',//搜索框提示词
    searchType: "exact",//搜索类型
    rules: {
        departmentName: [
            { required: true, message: '请输入部门名称', trigger: 'blur' },
        ],
        manage: [
            { required: true, message: '请输入负责人', trigger: 'blur' },
        ],
        contact: [
            { required: true, message: '请输入联系电话', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
        ],
        departmentDescription: [
            { required: true, message: '请输入简介', trigger: 'blur' },
        ]
    },

    // 批量上传
    uploadDialogVisible: false,
    uploadStutas: false,
    // 是否禁用上传
    isUploading: false,
    // 解析后的表格数据
    parseTableData: [],
    parsePage: {
        total: "",
        pageNum: 1,
        pageSize: 5,
    }
})
const editForm = ref()
const addForm = ref()
// 初始化
const init = async () =>
{
    const res = await departmentRead({ pageSize: state.pageSize, pageNum: state.pageNum, departmentName: state.stateData, searchType: state.searchType })
    if (res.meta.status == 200) {
        state.departmentList = res.data.depData
        state.total = res.data.total
        state.pageSize = res.data.pageSize
        state.pageNum = res.data.pageNum
    } else {
        // 提示获取资源失败
        ElMessage({
            type: 'info',
            message: "获取资源失败",
        })
    }
}
// 分页
const handlehSizeChange = (val) =>
{
    state.pageSize = val;
    state.pageNum = 1;
    init()
}
const handlehCurrentChange = (val) =>
{
    state.pageNum = Math.ceil(val);
    init()
}
//  搜索查找
const inputSearch = () =>
{
    state.searchType = 'fuzzy' //执行模糊搜索
    init()
}
// 搜索
let timeout
// 触发过滤条件
const querySearchAsync = (queryString, cb) =>
{
    const results = queryString
        ? state.departmentNames.filter(createFilter(queryString))
        : state.departmentNames

    clearTimeout(timeout)
    timeout = setTimeout(() =>
    {
        cb(results)
    }, 3000 * Math.random())
}
// 创建过滤
const createFilter = (queryString) =>
{
    return (restaurant) =>
    {
        return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
    }
}
// 搜索框选择
const handleSelect = (item) =>
{
    state.stateData = item.value
    init()
    console.log(state.stateData, "搜索词")
}
// 搜索框关键词
const getAllDepartmentNames = async () =>
{
    const { departmentList } = await findAllDepartmentList()
    state.departmentNames = departmentList
    console.log(state.departmentNames, "搜索词")

    state.departmentNames = state.departmentNames.map(function (item)
    {
        return { value: item };
    });
}
// 打开编辑窗口
const openUpdata = (row) =>
{
    state.editForm = {
        departmentID: row.DepartmentID,
        departmentName: row.DepartmentName,
        departmentDescription: row.DepartmentDescription,
        manage: row.Manage,
        contact: row.Contact,
    }

    state.editDialogVisible = true
}
// 选择
const handleSelectionChange = (selection) =>
{
    console.log("选择的id", selection);
    state.selectedIds = selection.map(item => item.DepartmentID);
    console.log("选择的id", state.selectedIds);
}
// 批量删除
const deleteAll = () =>
{
    if (state.selectedIds.length === 0) {
        // 如果没有选择序号，显示提示
        ElMessage({
            showClose: true,
            message: '请选择序号',
            type: 'warning',
        })
    } else {
        // 弹出确认删除的对话框
        ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(async () =>
            {
                // 用户点击确定，执行删除操作
                let deleteStatus = true;

                for (const item of state.selectedIds) {
                    const res = await departmentDelete({ departmentID: item });
                    console.log(res);

                    // 如果删除操作失败
                    if (res.meta.status !== 200) {
                        deleteStatus = false;
                        break;  // 停止循环，不再继续删除剩余的项
                    }
                }

                // 根据删除操作的状态值显示相应的提示
                if (deleteStatus) {
                    ElMessage({
                        showClose: true,
                        message: '删除成功',
                        type: 'success',
                    });
                } else {
                    ElMessage({
                        showClose: true,
                        message: '删除失败',
                        type: 'error',
                    });
                }

                // 删除完成后执行初始化或其他操作
                init();
            })
            .catch(() =>
            {
                ElMessage('已取消')
                // 用户点击取消，不执行任何操作
            });
    }
};
// 删除
const deleteRow = (row) =>
{
    // 弹出确认删除的对话框
    ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () =>
        {
            // 用户点击确定，执行删除操作
            const res = await departmentDelete({ departmentID: row.DepartmentID });
            if (res.meta.status !== 200) {
                // 如果删除操作失败
                ElMessage({
                    showClose: true,
                    message: '删除成功',
                    type: 'success',
                });
            } else {
                ElMessage({
                    showClose: true,
                    message: '删除失败',
                    type: 'error',
                });
            }
            // 删除完成后执行初始化或其他操作
            init();
        })
        .catch(() =>
        {
            ElMessage('已取消');
            // 用户点击取消，不执行任何操作
        });
}

// 编辑
const updateRow = () =>
{
    if (state.editDialogVisible) {
        editForm.value.validate((valid) =>
        {
            if (valid) {
                ElMessageBox.confirm('确定修改吗', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () =>
                {
                    const res = await departmentUpdate(state.editForm)
                    if (res.meta.status == 200) {
                        ElMessage({
                            showClose: true,
                            message: '修改成功',
                            type: 'success',
                        })
                        state.editDialogVisible = false
                        state.editForm = {}
                        init()
                    }
                }).catch(() =>
                {
                    ElMessage({
                        showClose: true,
                        message: '已取消',
                        type: 'info',
                    })
                })
            }
        })
    }
    if (state.addDialogVisible) {
        addForm.value.validate((valid) =>
        {
            if (valid) {
                ElMessageBox.confirm('确定新增吗', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () =>
                {
                    const res = await departmentCreate(state.editForm)
                    if (res.meta.status == 200) {
                        ElMessage({
                            showClose: true,
                            message: '新增成功',
                            type: 'success',
                        })
                        state.addDialogVisible = false
                        state.editForm = {}
                        init()
                    }
                }).catch(() =>
                {
                    ElMessage({
                        showClose: true,
                        message: '已取消',
                        type: 'info',
                    })
                })
            }
        })
    }



}

// 下载模板or下载数据表
const downloadUser = async (key) =>
{
    const colsList = [ //设置表格的宽度
        {
            wpx: 50, //序号
        },
        {
            wpx: 50, //部门
        },
        {
            wpx: 100, //负责人
        },
        {
            wpx: 50, //联系方式
        },
        {
            wpx: 100, //简介
        },
    ];
    const tableHeader = [
        "序号",
        "部门",
        "负责人",
        "联系方式",
        "简介",
    ]
    const positionObj = { start_r: 0, start_c: 0, end_r: 0, end_c: 3 }
    if (key == 'downLoad') {
        const instructions = [
            "导入说明.\n" +
            "1. 请不要改动Excel表结构并严格按照导入规则进行导入，否则将导入失败或出现不可预知的问题.\n" +
            "2. 请使用手机号码或者邮箱作为用户登录账号，用户的邮箱和手机号必须保证唯一性.\n" +
            "3. 登录密码默认为123456.\n" +
            "4. 所属部门名称必须与系统内已有的部门名称一致，否则将导致无法正常分配部门.\n" +
            "5. 所属权限名称必须与系统内已有的权限名称一致，否则将导致无法正常分配权限.\n" +
            "6. 请勿修改数据表结构，否则将导入失败的注明."
        ]
        const tableNameTemplate = "部门注册模板表"
        downloadTemplateUser(instructions, tableHeader, colsList, tableNameTemplate, positionObj)
    }
    else {
        const tableName = "部门注册数据表"
        const tableData = await departmentReadAll()
        for (let item of tableData.data.tableData) {
            // 获取用户类型名称  
            if (item.UserType) {
                item.UserType = item.UserType.UserTypeName;
            }

            // 获取部门名称  
            if (item.Department) {
                item.Department = item.Department.DepartmentName;
            }
        }
        let dataRows = tableData.data.tableData.map(obj => Object.values(obj));
        let titleRow = ['部门数据表'];
        downloadUserData(tableHeader, titleRow, dataRows, colsList, tableName, positionObj)
    }
}

//上传文件之前的钩子
const beforeUpload = async (file) =>  
{
    const tableJson = await analysisExcel(file)
    state.uploadStutas = true
    console.log(tableJson.tableData, "========>");

    for (let index = 0; index < tableJson.tableData.length; index++) {
        const item = tableJson.tableData[index];
        state.parseTableData[index] = {
            id: item[0],
            departmentName: item[1],
            manage: item[2],
            contact: item[3],
            departmentDescription: item[4],
        }
    }
    state.parsePage.total = state.parseTableData.length
    console.log(state.parseTableData, "=====111===>");
}

const upload = ref()
// 提交上传文件
const submitFileForm = () =>
{
    console.log(state.userTypeNameList, "=======>");
    if (state.uploadStutas) {
        for (let index = 0; index < state.parseTableData.length; index++) {
            state.editForm = state.parseTableData[index];
            console.log(state.editForm, "即将注册的部门数据");
            departmentCreate(state.editForm).then(res =>
            {
                ElMessage({
                    showClose: true,
                    message: '新增成功',
                    type: 'success',
                })
                state.uploadStutas = false
                state.uploadDialogVisible = false
                init()
            })
        }

    } else {
        upload.value.submit();
    }
}

// 解析数据分页
// 分页
const handleSizeChange = (val) =>
{
    console.log(`每页 ${val} 条`)
    state.parsePage.pageSize = val
}
const handleCurrentChange = (val) =>
{
    console.log(`当前页: ${val}`);
    state.parsePage.pageNum = val;
}
// 计算分页数据
const paginatedData = computed(() =>
{
    const startIndex = (state.parsePage.pageNum - 1) * state.parsePage.pageSize;
    const endIndex = startIndex + state.parsePage.pageSize;
    return state.parseTableData.slice(startIndex, endIndex);
})


onMounted(() =>
{
    init()
    getAllDepartmentNames()
})
</script>

<style lang="scss" scoped></style>